<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

class Books extends Model{

    //指定表名
    protected $table= 'books';
    //指定主键
    protected $primaryKey= 'id';
    //允许批量赋值字段
    protected $fillable = ['name','image','type','writer','intro','is_over','click_num','crawl_url','crawl_list','sort','status','new_chapter','chapter_count'];

    protected $hidden = [
        'crawl_url','crawl_list','pivot'
    ];

    public $timestamps = true;

    const SELECT_FIELD = ['id','name','image','writer','intro','is_over','type','click_num','updated_at','new_chapter','chapter_count'];

    public function getIsOverAttribute(int $value)
    {
        return $value == 1 ? '连载':'完结';
    }

    public function getTypeAttribute(int $value)
    {
        return get_bookType($value);
    }

    /**
     * 获取小说列表
     * @param array $where
     * @param array $field
     * @param array $order
     * @param bool $limit 是否需要分页
     * @param int $pageSize
     * @return array
     * */
    public static function getBookList(array $where=[],array $field=[],array $order=[],bool $limit=true,int $pageSize=null)
    {
        $page = Input::get('page',1);
        if (empty($pageSize)){
            $pageSize = Input::get('pageSize',10);
        }

        if (empty($field)){
            $field = self::SELECT_FIELD;
        }
        $sql = Books::select($field)
            ->where('status',1)
            ->when($where,function ($query)use($where){
                foreach ($where as $key=>$item) {
                    //一维数组
                    if (is_array($item)) {
                        $op = str_replace(' ', '', strtolower($item[0]));
                        switch ($op) {
                            case 'in':
                                $query->whereIn($key,$item[1]);
                                break;
                            case 'notin':
                                $query->whereNotIn($key,$item[1]);
                                break;
                            case 'raw':
                                $query->whereRaw($item[1]);
                                break;
                            default:
                                $query->where($key,$op,$item[1]);
                                break;
                        }
                    } else {
                        $query->where($key,$item);
                    }
                }
            })
            ->when($order,function ($query)use($order){
                foreach ($order as $key=>$item){
                    if (is_array($item)) {
                        $op = str_replace(' ', '', strtolower($item[0]));
                        switch ($op) {
                            case 'raw':
                                $query->orderByRaw($item[1]);
                                break;
                            default:
                                $query->orderBy($op,$item[1]);
                                break;
                        }
                    } else {
                        $query->orderBy($key,$item);
                    }
                }
            })
            ->orderBy('sort','desc');
        if ($pageSize < 0){
            return $sql->get()??[];
        }
        if ($limit == true){
            return $sql->paginate($pageSize);
        }else{
            return $sql->skip(($page-1)*$pageSize)->take($pageSize)->get();
        }
    }


    /**
     * 根据bookId 获取小说详情(cache)
     * @param int $bookId
     * @return array
     * */
    public static function getBookDetailById(int $bookId)
    {
        $key = config('cacheKey.bookDetail').$bookId;
        $bookDetail = Redis::get($key);
        if (empty($bookDetail)){
            $bookDetail = Books::select(self::SELECT_FIELD)->find($bookId);
            if (empty($bookDetail)){
                Redis::setex($key,30,[]);
            }else{
                $bookDetail['first_chapter_id'] = self::getFirstChapterIdById($bookId);
                $bookDetail['last_chapter_id'] = self::getLastChapterIdById($bookId);
                Redis::setex($key,86400*7,$bookDetail);
            }
        }else{
            $bookDetail = json_decode($bookDetail,true);
        }
        return $bookDetail;
    }

    /**
     * 根据bookId 获取小说章节列表(cache)
     * @param int $bookId
     * @return array
     * */
    public static function getBookChapterList(int $bookId)
    {
        $key = config('cacheKey.chapterList').$bookId;
        $chapterList = Redis::get($key);
        if (empty($chapterList)){
            /*最新章节列表*/
            $chapter_tableName = chapterTableNameByBookId($bookId);
            /*章节列表*/
            $chapterList = DB::table($chapter_tableName)
                ->select(['id','book_id','title','created_at'])
                ->whereBook_id($bookId)
                ->orderBy('sort','asc')
                ->get();
            if (!empty($chapterList)){
                Redis::setex($key,86400*7,$chapterList);
            }else{
                Redis::setex($key,30,$chapterList);
            }
        }else{
            $chapterList = json_decode($chapterList,true);
        }
        return $chapterList;
    }



    /**
     * 根据小说ID实时获取小说章节总数
     * @param int $bookId
     * @return int $count
     * */
    public static function getChapterCountById(int $bookId)
    {
        //更新章节总数
        $chapter_tableName = chapterTableNameByBookId($bookId);
        /*获取章节总数*/
        $count = DB::table($chapter_tableName)
            ->whereBook_id($bookId)
            ->count();
        return $count;
    }

    /**
     * 刷新小说详情缓存
     * @param int $bookId
     * @return bool
     * */
    public static function updateBookCache(int $bookId)
    {
        //删除小说详情缓存
        $key = config('cacheKey.bookDetail').$bookId;
        Redis::del($key);
        //刷新缓存
        self::getBookDetailById($bookId);

        //删除小说章节列表缓存
        $key = config('cacheKey.chapterList').$bookId;
        Redis::del($key);
        //刷新缓存
        self::getBookChapterList($bookId);

        return true;
    }
    
    /**
     * 根据小说ID 获取第一章节ID
     * @param int $bookId
     * @return int $firstChapterId
     * */
    public static function getFirstChapterIdById(int $bookId)
    {
        $chapter_tableName = chapterTableNameByBookId($bookId);
        $firstChapterId = DB::table($chapter_tableName)->whereBook_id($bookId)->orderBy('sort','asc')->first(['id']);
        return isset($firstChapterId->id)?$firstChapterId->id:'0';
    }

    /**
     * 根据小说ID 获取最后一章 章节节ID
     * @param int $bookId
     * @return int $lastChapterId
     * */
    public static function getLastChapterIdById(int $bookId)
    {
        $chapter_tableName = chapterTableNameByBookId($bookId);
        $lastChapterId = DB::table($chapter_tableName)->whereBook_id($bookId)->orderBy('sort','desc')->first(['id']);
        return isset($lastChapterId->id)?$lastChapterId->id:'0';
    }

}
